/*
 * BONDI API example - Calendar
 * The UI is minimal so that it doesn't interfere with the examples 
 * of the bondi.pim.calendar functionality.
 * 
 * Widget shows a list of calendar events.
 * 
 * The calendar events used in preview can be set in the
 * Calendar tab of the project.xml editor.
 * 
 * @see http://bondi.omtp.org/1.01/apis/calendar.html
 */

/**
 * Generic failure call back function.
 * The error call back is always provided with a GenericError
 * that can be queried for the cause of the failure.
 * @param error The {GenericError} error raised during asynchronous operation
 * @see http://bondi.omtp.org/1.01/apis/bondi.html#onErrorN10141
 */
var pimFailure = function(error) {
	showError(error.code);
};

function getSite(site){

	if (site == 'calendar') {
		location.href = 'calendar.html';
	} else if (site == 'birthday') {
		location.href = 'birthday.html';
	}
	else {
		location.href = 'index.html';			
	}
}

function showStatus(site){
	if (site == 'calendarInit') {
		var row = document.createElement("tr");
		var cell1 = document.createElement("td");
		var cell2 = document.createElement("td");
		var cell3 = document.createElement("td");
		
		var text1 = document.createTextNode('Kalender');
		var inp1 = document.createElement('INPUT');
		var inp2 = document.createElement('INPUT');
		
		inp1.setAttribute('type', 'button');
		inp1.setAttribute('value', 'Kalender');
		inp1.setAttribute('onclick', "showContent('calendarRefresh')");
			
		inp2.setAttribute('type', 'button');
		inp2.setAttribute('value', 'Geburtstage');
		inp2.setAttribute('onclick', "showContent('birthdayRefresh')");

		cell1.appendChild(text1);
		cell2.appendChild(inp1);
		cell3.appendChild(inp2);
		
		row.appendChild(cell1);
		row.appendChild(cell2);
		row.appendChild(cell3);

		document.getElementById("statusTable").appendChild(row);
		
	}
	if (site == 'calendarRefresh') {
		alert("Kalender wird geladen");
		try {
			var calendar = bondi.pim.calendar.getCalendars()[0];
			calendar.findEvents(showEventsNormal, pimFailure, null);
		}
		catch (error) {
			showError(error.code);
		}		
	}

	if (site == 'birthdayRefresh') {
		alert("Geburtstage werden geladen");
		try {
			var calendar = bondi.pim.calendar.getCalendars()[0];
			calendar.findEvents(showEventsBirthday, pimFailure, null);
		}
		catch (error) {
			showError(error.code);
		}		
	}


} 


function showContent(site){
	if (site == 'calendarInit') {
		alert("Content: Kalender wird geladen");
		try {
			var calendar = bondi.pim.calendar.getCalendars()[0];
			calendar.findEvents(showEventsNormal, pimFailure, null);
		}
		catch (error) {
			showError(error.code);
		}		
	}
	if (site == 'calendarRefresh') {
		alert("Content: Kalender wird aktualisiert.");
		try {
			var calendar = bondi.pim.calendar.getCalendars()[0];
			calendar.findEvents(showEventsNormal, pimFailure, null);
		}
		catch (error) {
			showError(error.code);
		}		
	}
	if (site == 'birthdayRefresh') {
		alert("Content: Geburtstage wird aktualisiert.");
		try {
			var calendar = bondi.pim.calendar.getCalendars()[0];
			calendar.findEvents(showEventsBirthday, pimFailure, null);
		}
		catch (error) {
			showError(error.code);
		}		
	}
} 

/**
 * appInit is called from index.html when the html content has been loaded.
 * Example of bondi.pim.calendar.getCalendars and Calendar.findEvents
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#getCalendarsN101C4
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#findEventsN1042F
 */
function appInit() {
	showStatus('calendarInit');
	showContent('calendarInit');
}

/**
 * appInit is called from index.html when the html content has been loaded.
 * Example of bondi.pim.calendar.getCalendars and Calendar.findEvents
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#getCalendarsN101C4
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#findEventsN1042F
 */
function kalenderExpand() {
	
	try {

		var calendar = bondi.pim.calendar.getCalendars()[0];
		
		//addSampleEvents(calendar);
		
		// Calendar.findEvents is asynchronous.  
		// Our success call back is showEvents.
		calendar.findEvents(showEvents, pimFailure, null);
	}
	catch (error) {
		showError(error.code);
	}
}

/**
 * appInit is called from index.html when the html content has been loaded.
 * Example of bondi.pim.calendar.getCalendars and Calendar.findEvents
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#getCalendarsN101C4
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#findEventsN1042F
 */
function kalenderCollapse() {
	tbl=document.getElementById('kalenderTable');
	while(tbl.rows.length>0) {
		tbl.deleteRow(0);
	}
}

/**
 * Create some events so that our view is not empty.
 * Please note that a preview device calendar can also be specified 
 * in the Calendar tab of the project.xml editor.  
 * Example of Calendar.createEvent and Calendar.addEvent
 * @param list The {Calendar} calendar to use.
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#createEventN10225
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#addEventN102A3
 */
function addSampleEvents(calendar) {

	// Please note that the keys used in event creation must match the supported keys or
	// a DeviceAPIError.INVALID_ARGUMENT_ERROR will be thrown.  There can be missing keys,
	// but all keys specified must match exactly.
	var samples = [
	               { summary : "Group Lunch", description : "Come celebrate birthdays this month!", startTime: new Date, location : "Ivar's", recurrence: bondi.pim.calendar.MONTHLY_RECURRENCE},
	               { summary : "Status", description : "Write weekly status report", startTime: new Date, recurrence: bondi.pim.calendar.WEEKLY_RECURRENCE},
	               { summary : "Briefing", description : "Participate in daily executive discussion", startTime: new Date, location: "Board Room", recurrence: bondi.pim.calendar.DAILY_RECURRENCE},
	               { summary : "Networking", description : "Remember to upload new pictures and status", startTime: new Date},
	               ];
	
	for (var i in samples) {
		var event = calendar.createEvent(samples[i]);
		calendar.addEvent(event);
	}
}

/**
 * Iterate through our event list and display the details.
 * Example of Event properties
 * @param events The array of events to display
 * @see http://bondi.omtp.org/1.01/apis/task.html#Task
 */
function showEvents(events) {
	clearTable("kalenderTable", ["summary", "description", "date"]);
	                             //, "location", "recurrence"]);
	
	try {
		for (var i in events) {
			var event = events[i];
			addTableRow("kalenderTable", [,
			                      event.summary,
			                      event.description,
			                      event.startTime.getDate()+"."+
			                      (parseInt(event.startTime.getMonth())+1)+"."+
			                      event.startTime.getFullYear()
			                      //.toDateString()//,
			                      //event.location,
			                      //getRecurrence(event.recurrence)
			                      ]);
		}
	}
	catch (error) {
		showError(error.code);
	}
	
	// make sure we can see all the listing
	widget.window.setScroll(true);
}

/**
 * Iterate through our event list and display the details.
 * Example of Event properties
 * @param events The array of events to display
 * @see http://bondi.omtp.org/1.01/apis/task.html#Task
 */
function showEventsNormal(events) {
	clearTable("kalenderTable", ["summary", "description", "date"]);
	                             //, "location", "recurrence"]);
	
	try {
		for (var i in events) {
			var event = events[i];
			if ( bondi.pim.calendar.YEARLY_RECURRENCE != event.recurrence)
			{
			addTableRow("kalenderTable", [,
			                      event.summary,
			                      event.description,
			                      event.startTime.getDate()+"."+(parseInt(event.startTime.getMonth())+1)+"."+
			                      event.startTime.getFullYear()
			                      //.toDateString()//,
			                      //event.location,
			                      //getRecurrence(event.recurrence)
			                      ]);
			
			}
			
		}
	}
	catch (error) {
		showError(error.code);
	}
	
	// make sure we can see all the listing
	widget.window.setScroll(true);
}

/**
 * Iterate through our event list and display the details.
 * Example of Event properties
 * @param events The array of events to display
 * @see http://bondi.omtp.org/1.01/apis/task.html#Task
 */
function showEventsBirthday(events) {
	clearTable("kalenderTable", ["summary", "description", "date"]);
	                             //, "location", "recurrence"]);
	
	try {
		for (var i in events) {
			var event = events[i];
			if ( bondi.pim.calendar.YEARLY_RECURRENCE == event.recurrence)
			{
				
			
			addTableRow("kalenderTable", [,
			                      event.summary,
			                      event.description,
			                      event.startTime.getDate()+"."+
			                      (parseInt(event.startTime.getMonth())+1)+"."+
			                      event.startTime.getFullYear()
			                      //.toDateString()//,
			                      //event.location,
			                      //getRecurrence(event.recurrence)
			                      ]);
			
			}
		}
	}
	catch (error) {
		showError(error.code);
	}
	
	// make sure we can see all the listing
	widget.window.setScroll(true);
}

/**
 * Convert a recurrence constant into a user string.
 * Example of CalendarManager constants
 * @param recurrence The {number} recurrence constant
 * @return A user readable string
 * @see http://bondi.omtp.org/1.01/apis/calendar.html#CalendarManager
 */
function getRecurrence(recurrence) {
	var result;
	switch (recurrence) {
		case bondi.pim.calendar.DAILY_RECURRENCE:
			result = "daily";
			break;
		case bondi.pim.calendar.WEEKLY_RECURRENCE:
			result = "weekly";
			break;
		case bondi.pim.calendar.MONTHLY_RECURRENCE:
			result = "monthly";
			break;
		case bondi.pim.calendar.YEARLY_RECURRENCE:
			result = "yearly";
			break;
		case bondi.pim.calendar.NO_RECURRENCE:
		default:
			result = "-";
			break;
	}
	return result;
}

/**
 * Turn an error code into a message.
 * Example of using BONDI error codes.
 * @param code The {number} exception code
 * @return A readable message corresponding to code
 * @see http://bondi.omtp.org/1.01/apis/bondi.html#DeviceAPIError
 * @see http://bondi.omtp.org/1.01/apis/gallery.html#GalleryError
 */
function getErrorMessage(code) {
	var message;
	switch(code) {
		case DeviceAPIError.INVALID_ARGUMENT_ERROR:
			message = "invalid argument error";
			break;
		case DeviceAPIError.IO_ERROR:
			message = "i/o error during operation";
			break;
		case SecurityError.PERMISSION_DENIED_ERROR:
			message = "permission denied error - enable feature in project.xml";
			break;
		case DeviceAPIError.NOT_FOUND_ERROR:
			message = "not found error";
			break;
		case DeviceAPIError.NOT_SUPPORTED_ERROR:
			message = "function not supported";
			break;
		case DeviceAPIError.PENDING_OPERATION_ERROR:
			message = "pending operation error";
			break;
		default:
			message = "unknown error : " + code;
			break;
	}
	
	return message;
}

/**
 * Utility function to show a gallery error in our table.
 * @param code
 */
function showError(code) {
	clearTable("kalenderTable", ["Error"], [undefined]);
	
	var row = document.createElement("tr");
	row.appendChild(createTableCell("Exception: " + getErrorMessage(code)));
	document.getElementById("kalenderTable").appendChild(row);
}

/**
 * Utility function to create a table cell, and set the contents.
 * @param content The {String} text contents for cell
 * @return The newly created cell element
 */
function createTableCell(content) {
	var cell = document.createElement("td");
	cell.appendChild(document.createTextNode(content));
	return cell;
}

/**
 * Utility function to add a row with an icon to a table.
 * @param id The {String} document id of table body 
 * @param cells The array of cell contents 
 */
function addTableRow(id, cells) {
	var row = document.createElement("tr");
	for (var i in cells) {
		row.appendChild(createTableCell(cells[i]));
	}
	document.getElementById(id).appendChild(row);
}

/**
 * Utility function to clear the rows of a table.
 * @param id The {String} document id of table body 
 * @param headers The {array} contents of headers
 */
function clearTable(id, headers) {
	var table = document.getElementById(id);
	for (var i = table.rows.length-1; i >= 0; i--) {
		table.deleteRow(i);
	}
	
	var row = document.createElement("tr");
	for (var i in headers) {
		var header = document.createElement("th");
		header.appendChild(document.createTextNode(headers[i]));
		row.appendChild(header);
	}
	
	table.appendChild(row);
}